<?php

namespace App\Console\Commands\Fix;

use App\Console\BaseCommand;
use App\Consts\GlobalConst;
use App\Consts\GlobalCounterConst;
use App\Models\FakeArticle;
use App\Models\SysArticle;
use Illuminate\Database\Query\Builder;

/**
 * 假数据修复脚本
 * Class FakeFixCommand
 * @package App\Console\Commands\Fix
 */
class FakeFixCommand extends BaseCommand
{

    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'fix:fake {action}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'fake data for article';

    /**
     * 假数据 - 文章推荐
     * @return int
     */
    public function article()
    {
        $subMode = $this->_getSubModel();
        $finish = $subMode->count();
        // 每 100 单位合并处理一次
        $subMode->chunkById(100, function ($list) use ($finish) {
            foreach ($list as $item) {
                static $index = 1;
                $id = $item->article_id;
                $count = mt_rand(20,50);
                $fake = FakeArticle::getModel()
                    ->where(['action_type' => GlobalCounterConst::ACTION_TYPE_RECOMMEND])
                    ->where('article_id', $id)
                    ->first();
                if (!$fake) {
                    $data = [
                        'article_id' => $id,
                        'action_type' => GlobalCounterConst::ACTION_TYPE_RECOMMEND,
                        'count' => $count
                    ];
                    FakeArticle::getModel()->create($data);
                    $info = "[$index/$finish] insert fake data to `fake_article` - " . json_encode($data);

                } else {
                    $info = "[$index/$finish] check fake data - article id - " . $id;
                }
                // log info
                $this->info($info);
                if (!$fake) $this->logger($info, false, 'script');
                $index++;
            }
        }, 'article_id');
        return 1;
    }

    /**
     * get sub model
     * @return \Illuminate\Database\Eloquent\Builder|\Illuminate\Database\Eloquent\Model|mixed
     */
    private function _getSubModel()
    {
        $subMode = SysArticle::getSubModel(function (Builder $query) {
            $query->where('is_deleted', GlobalConst::IS_NOT_DELETE);
            $query->where('is_shield', GlobalConst::IS_NOT_SHIELD);
        }, ['id', 'article_id']);
        return $subMode;
    }

}
